<template>
  <el-form label-width="100px" v-loading="loading">
    <el-form-item label="sku名称">
      <el-input placeholder="sku名称" v-model="skuParams.skuName" />
    </el-form-item>
    <el-form-item label="价格（元）">
      <el-input placeholder="价格（元）" type="number" v-model="skuParams.price" />
    </el-form-item>
    <el-form-item label="重量（g）">
      <el-input placeholder="重量（g）" type="number" v-model="skuParams.weight" />
    </el-form-item>
    <el-form-item label="sku描述">
      <el-input placeholder="sku描述" type="textarea" :row="2" v-model="skuParams.skuDesc" />
    </el-form-item>

    <el-form-item label="平台属性">
      <el-form :inline="true" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in attrArr" :key="item.id">
            <el-form-item :label="item.attrName" class="plat-attr">
              <!-- 先将收集到的数据挂载到attrName上，因为他是遍历的对象，之后保存是在拿出来 -->
              <el-select v-model="item.attrIdAndValueId">
                <el-option :label="attrValue.valueName" v-for="attrValue in item.attrValueList" :key="attrValue.id" :value="`${item.id}:${attrValue.id}`" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-form :inline="true" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in saleArr" :key="item.id">
            <el-form-item :label="item.saleAttrName" class="plat-attr">
              <el-select v-model="item.saleIdAndValueId">
                <el-option :label="saleAttrValue.saleAttrValueName" v-for="(saleAttrValue, index) in item.spuSaleAttrValueList" :key="saleAttrValue.id" :value="`${item.id}:${saleAttrValue.id}`" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-form-item>

    <el-form-item label="图片名称">
      <el-table border :data="imgArr" ref="tableRef">
        <el-table-column type="selection" width="80px" align="center" />
        <el-table-column label="图片" align="center">
          <template #="{ row }">
            <el-image :src="row.imgUrl" fit="cover" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="imgName" />
        <el-table-column label="操作" align="center">
          <template #="{ row }">
            <el-button type="warning" size="small" @click="setDefaultImg(row)">设置默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue'
  import { ElTable } from 'element-plus'
  import { reqAttr } from '@/api/product/attr'
  import { reqSpuImageList, reqSpuHasSaleAttr, reqAddSku } from '@/api/product/spu'
  import { SaleAttr, SpuData, SpuImg, SkuData } from '@/api/product/spu/type'
  import { getElMessage } from '@/utils/message'
  import { Attr } from '@/api/product/attr/type'
  const $emit = defineEmits(['changeScene'])

  const loading = ref<boolean>(false)
  const attrArr = ref<Attr[]>([])
  const saleArr = ref<SaleAttr[]>([])
  const imgArr = ref<SpuImg[]>([])
  const skuParams = reactive<SkuData>({
    category3Id: '',
    spuId: '',
    tmId: '',
    skuName: '',
    price: '',
    weight: '',
    skuDesc: '',
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
    skuDefaultImg: '',
  })
  function initSkuData(c1Id: number | string, c2Id: number | string, supData: SpuData) {
    loading.value = true
    Object.assign(skuParams, {
      category3Id: supData.category3Id,
      spuId: supData.id!,
      tmId: supData.tmId,
      skuName: '',
      price: '',
      weight: '',
      skuDesc: '',
      skuAttrValueList: [],
      skuSaleAttrValueList: [],
      skuDefaultImg: '',
    })

    let r1 = getReqAttr(c1Id, c2Id, supData.category3Id)
    let r2 = getReqSpuHasSaleAttr(supData.id as number)
    let r3 = getReqSpuImageList(supData.id as number)
    Promise.all([r1, r2, r3]).finally(() => (loading.value = false))
  }

  const tableRef = ref<InstanceType<typeof ElTable>>()
  function setDefaultImg(row: SpuImg) {
    imgArr.value.forEach((item) => {
      tableRef.value?.toggleRowSelection(item, false)
    })

    tableRef.value?.toggleRowSelection(row, true)
    skuParams.skuDefaultImg = row.imgUrl!
  }

  async function save() {
    // 整理参数
    // 平台属性
    skuParams.skuAttrValueList = attrArr.value.reduce((prev: any, next: any) => {
      if (next.attrIdAndValueId) {
        let [attrId, valueId] = next.attrIdAndValueId.split(':')
        prev.push({
          attrId,
          valueId,
        })
      }
      return prev
    }, [])

    // 销售属性
    skuParams.skuSaleAttrValueList = saleArr.value.reduce((prev: any, next: any) => {
      if (next.saleIdAndValueId) {
        let [saleAttrId, saleAttrValueId] = next.saleIdAndValueId.split(':')
        prev.push({
          saleAttrId,
          saleAttrValueId,
        })
      }
      return prev
    }, [])

    try {
      const res = await reqAddSku(skuParams)
      if (res.code === 200) {
        getElMessage('新增sku成功', 'success')
        $emit('changeScene', { flag: 0 })
      } else {
        getElMessage('新增sku失败', 'success')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'success')
    }
  }

  function cancel() {
    $emit('changeScene', { flag: 0 })
  }
  async function getReqAttr(c1Id: number | string, c2Id: number | string, c3Id: number | string) {
    try {
      const res = await reqAttr(+c1Id, +c2Id, +c3Id)
      attrArr.value = res.data
    } catch (error) {
      getElMessage('获取平台属性失败', 'error')
    }
  }
  async function getReqSpuImageList(supId: number | string) {
    try {
      const res = await reqSpuImageList(+supId)
      imgArr.value = res.data
    } catch (error) {
      getElMessage('获取平台图片列表失败', 'error')
    }
  }
  async function getReqSpuHasSaleAttr(supId: number | string) {
    try {
      const res = await reqSpuHasSaleAttr(+supId)
      saleArr.value = res.data
    } catch (error) {
      getElMessage('获取平台已有属性列表失败', 'error')
    }
  }

  defineExpose({
    initSkuData,
  })
</script>

<style lang="scss" scoped>
  .el-form--inline {
    width: 100%;
    .el-row {
      width: 100%;
      .plat-attr {
        width: 100%;
        .el-select {
          width: 100%;
        }
      }
    }
  }
</style>
